import logger from './logger';
import settingHelper from './settingHelper';
import common from '@ohos.app.ability.common';
import preferences from '@ohos.data.preferences';

export default class db {
  private context: common.Context;
  private static _instance: db;

  public static get instance(): db {
    return this._instance;
  }

  public static createInstance(context: common.Context): db {
    if (this._instance == null) {
      this._instance = new db(context);
      settingHelper.init();
    }
    return this._instance;
  }

  private constructor(context: common.Context) {
    this.context = context;
  }

  query(key: string): Promise<preferences.ValueType> {
    return new Promise((resolve) => {
      try {
        preferences.getPreferences(this.context, 'db', function (err, preferences) {
          if (!err) {
            preferences.get(key, '', function (err, value) {
              if (!err)
                resolve(value);
              else
                resolve('');
            });
          } else
            resolve('');
        });
      } catch (e) {
        logger.error(e);
        resolve('');
      }
    });
  }

  update(key: string, value: preferences.ValueType) {
    try {
      preferences.getPreferences(this.context, 'db', function (err, preferences) {
        if (!err) {
          preferences.put(key, value);
          preferences.flush();
        }
      });
    } catch (e) {
      logger.error(e);
    }
  }
}